package cn.itsource.ymcc.consumer;

import cn.itsource.ymcc.constant.*;
import cn.itsource.ymcc.domain.CourseOrder;
import cn.itsource.ymcc.domain.CourseOrderItem;
import cn.itsource.ymcc.domain.PayOrder;
import cn.itsource.ymcc.mapper.PayOrderMapper;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Component;

import java.io.UnsupportedEncodingException;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Component
@RocketMQMessageListener(
        consumerGroup = "PayToCourseOrderConsumer",
        topic = OrderConstants.MQ_TOPIC_ORDER_TO_PAYORDER,
        selectorExpression = OrderConstants.MQ_TAGS_ORDER_TO_PAYORDER
)
public class PayToCourseOrderConsumer implements RocketMQListener<MessageExt> {
    @Autowired
    private PayOrderMapper payOrderMapper;
    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    @Override
    public void onMessage(MessageExt messageExt) {
        try {
            byte[] body = messageExt.getBody();
            String message = new String(body, Constants.UTF8);
            CourseOrder courseOrder = JSON.parseObject(message, CourseOrder.class);
            //创建支付单
            PayOrder payOrder = new PayOrder();
            payOrder.setCreateTime(new Date());
            payOrder.setAmount(courseOrder.getPayAmount());
            payOrder.setPayType(courseOrder.getPayType());
            List<CourseOrderItem> itemList = courseOrder.getItemList();

            String collect = itemList.stream().map(item -> item.getCourseId().toString()
            ).collect(Collectors.joining(","));
            payOrder.setRelationId(collect);//保存课程id
            payOrder.setOrderNo(courseOrder.getOrderNo());
            payOrder.setUserId(courseOrder.getUserId());
            payOrder.setSubject(courseOrder.getTitle());
            payOrder.setPayStatus(RConst.Num.INT_0);
            payOrderMapper.insert(payOrder);

            //在生产支付单的时候去就发送一个延迟消息
            rocketMQTemplate.syncSend(PayConstants.TOPIC_PAY_ORDER_DELAY_MESSAGE+":"+PayConstants.TAGS_PAY_ORDER_DELAY_MESSAGE,
                    MessageBuilder.withPayload(courseOrder.getOrderNo()).build(),
                    2000,//连接超时时间
                    5);//多少就去发送这个消息

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }
}
